/**
 * PayRoller Utility javascript library v1.0
 * 
 * @author Rodrigo Longhi
 * @version 1.0
 */

Payroller.util = {

	lastId: null,

	/**
	 * Draw the table based on params
	 * 
	 * @param: args [name: '', options: {}, values(), fields(), columns()]
	 */
	draw: function(args) {

		// parameter validation
		if (!args.options)
			args.options = {
				edit: false,
				remove: false
			};

		var content = '';
		$('#' + args.name).empty();

		// fill columns
		var cols = args.columns();
		for (var i in cols)
			content += '<th width="' + cols[i].width + '">' + cols[i].label + '</td>';

		// extra options
		if (args.options.edit)
			content += '<th></td>';
		if (args.options.remove)
			content += '<th></td>';

		$('#' + args.name).append('<tr>' + content + '</tr>');

		// add items
		var values = args.values();
		var fields = args.fields();

		for (var i in values) {
			content = '';

			// add column for each field
			for (var j in fields)
				content += '<td>' + (fields[j].prefix ? fields[j].prefix : '') + values[i][fields[j].name] + '</td>';

			// extra options
			if (args.options.edit)
				content += '<td align="center"><button type="button" onclick="' + args.options.ns + '.open(' + args.options.ns + '.items[' + i + '], ' + i + ');"><img src="img/pencil.png" alt="Edit" /></button></td>';
			if (args.options.remove)
				content += '<td align="center"><button type="button" onclick="' + args.options.ns + '.remove(' + i + ');"><img src="img/delete.png" alt="Delete" /></button></td>';

			$('#' + args.name).append('<tr>' + content + '</tr>');
		}

		$('#' + args.name + ' button').button();
	},

	/**
	 * Persist data into localStorage based on params
	 * 
	 * @param: args
	 */
	persist: function(args) {
	
		// store collection size
		localStorage[args.key + '.count'] = args.values.length;
		
		this.log('Saving localStorage... ' + args.key);
		this.log(args.key + '.count = ' + args.values.length);
		
		// store each item
		for (var i in args.values) {
			for (var j in args.values[i]) {
				
				// computes keys and values
				var key = (args.key + '.' + i + '.' + j);
				var values = args.values[i][j];
				
				if((typeof values) == 'object')
					this.persist({ key: key, values: values });
				else {
					localStorage[key] = values;
					this.log(key + ' = ' + values + ' (' + (typeof values) + ')');
				}
			}
		}
	},
	
	/**
	 * Append text to log area
	 * 
	 * @param: text
	 */
	log: function(text) {
		$('#logger').append('<p>' + text + '</p>');
	},

	/**
	 * Retrieve values from localStorage
	 * 
	 * @param: key
	 */
	retrieve: function(key) {
		var data = [];
		var id = 0;

		// control variables
		var limit = localStorage[key + '.count']; // amount of data expected
		
		this.log('Reading localStorage... for ' + key);
		this.log(key + '.count = ' + limit);

		// search in the entire storage
		for (var i in localStorage) {
			// check if storage id match key
			if (i.indexOf(key) == -1)
				continue;
			
			var path = i.replace(key + '.', '').split('.');
			var index = path[0];
			var attr = path[1];

			if ((/\d/).exec(index) != null) {
				if (index > (limit - 1)) {
					delete localStorage[i];
					continue;
				}
				
				this.log(i + ' - ' + localStorage[i]);

				// prepare data array
				while(data[index] == null)
					data.push({});

				// prepare recursion
				if (path.length > 2) {
					if (data[index][attr] != null)
						continue;

					data[index][attr] = this.retrieve(key + '.' + index + '.' + attr);
				} else
					// fill objects data
					data[index][attr] = (isNaN(localStorage[i]) ? localStorage[i] : parseFloat(localStorage[i]));

				// save last id used
				if (attr == 'id' && localStorage[i] > id)
					id = localStorage[i];
			}
		}
		
		this.log('<hr/>');

		// sets the last readed id on a local attribute
		this.lastId = id;

		return data;
	},

	/**
	 * Creates default dialog
	 * 
	 * @param: args
	 */
	dialog: function(args) {
		$('#' + args.name).dialog({
			closeOnEscape: false,
			autoOpen: false,
			resizable: false,
			height: 'auto',
			width: 450,
			modal: true,
			buttons: {
				'Save': args.callback,
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
	},

	/**
	 * Open dialog in a dafault manner
	 * 
	 * @param: dialog
	 */
	pop: function(dialog) {
		this.clean(dialog);

		$('#' + dialog.name).dialog('open');
	},

	/**
	 * Clear dialog inputs and reset cursor position
	 * 
	 * @param: dialog
	 */
	clean: function(dialog) {
		$('#' + dialog.name + ' input').val('');
		$('#' + dialog.name + '-' + dialog.focus).focus();
	},

	/**
	 * Fill dialog with data information
	 * 
	 * @params: dialog and data
	 */
	fill: function(dialog, data) {
		for (var i in data)
			$('#' + dialog.name + '-' + i).val(data[i]);
	},

	/**
	 * Parse JSON object into string
	 * 
	 * TODO: detect object and do recursively
	 * 
	 * @params
	 */
	stringfy: function(obj) {
		var json = [];
		var attr = null;

		for (var attr in obj)
			json.push('\'' + attr + '\' : \'' + obj[attr] + '\'');
			//if(typeof obj[attr] == 'object')
				//json.push('\'' + attr + '\' : ' + this.stringfy(obj[attr]));
			//else
		
		return '{ ' + json.join(', ') + ' }';
	},

	/**
	 * Debug PayRoller data into an alert
	 * 
	 * @param: null
	 */
	debug: function() {
		var msg = 'localStorage: ' + localStorage.length + '\n';

		// fill items
		msg += '\nExpenses: ' + $E.items.length + '\n';
		for (var i in $E.items)
			msg += $E.items[i].id + ' - ' + $E.items[i].name + ' = ($' + $E.items[i].value + ')\n';

		// fill people involved
		msg += '\nPeople: ' + $G.items.length + '\n';
		for (var i in $G.items) {
			msg += $G.items[i].id + ' - ' + $G.items[i].name + '\n';

			for (var j in $G.items[i].split)
				msg += 'E: ' + $G.items[i].split[j].id + ' | ' + $G.items[i].split[j].type + ' = (' + $G.items[i].split[j].value + ') [+' + $G.items[i].split[j].handicap + ']\n';
		}

		alert(msg);
	},
	
	/**
	 * Dump collection data into the log area
	 * 
	 * @param collection[]
	 */
	dump: function(data) {
		var text = '';
		
		// iterates through list items
		for(var i in data) {			
			text += '<ul>';

			// iterates on each field
			for(var j in data[i]) {
				if(typeof data[i][j] == 'object')
					text += this.dump(data[i][j]);
				else
					text += '<li class="log">' + j + ': ' + data[i][j] + '</li>';
			}
			
			text += '</ul>';
		}
		
		return text;
	}	
};

if (typeof $U == 'undefined')
	$U = Payroller.util;
else
	alert('PayRoller Error: $U cannot be used.');